package com.example.treeHole.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.treeHole.Annotation.Authority;
import com.example.treeHole.Enum.AuthorityEnum;
import com.example.treeHole.exception.CustomException;
import com.example.treeHole.service.UserService;
import com.example.treeHole.utils.BaseContext;
import com.example.treeHole.vo.UserInfo;
import org.apache.maven.artifact.repository.Authentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.security.GeneralSecurityException;

/**
 * jwt拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从http请求的header中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 如果没拿到，我再去参数里面拿一波试试  /api/admin?token=xxxxx
            token = request.getParameter("token");
        }
        // 2. 开始执行认证
        if (StrUtil.isBlank(token)) {
            throw new CustomException("无token，请重新登录");
        }
        // 获取 token 中的userId
        String userId;
        UserInfo user;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            // 根据token中的userid查询数据库
            user = userService.findById(userId);
        } catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + ", token=" + token, e);
            throw new CustomException(errMsg);
        }
        if (user == null) {
            throw new CustomException("用户不存在，请重新登录");
        }
        //进行接口权限验证
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            // 检查方法上是否有MyAnnotation注解
            if (method.isAnnotationPresent(Authority.class)) {
                Authority myAnnotation = method.getAnnotation(Authority.class);
                AuthorityEnum annotationValue = myAnnotation.value();
                int value = annotationValue.getValue();
                if(user.getRoleType()<value){
                    try {
                        throw new GeneralSecurityException("抱歉您的权限不够，请联系超管");
                    } catch (GeneralSecurityException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
        try {
            // 用户密码加签验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new CustomException("token验证失败，请重新登录");
        }
        BaseContext.setCurrentId(userId);
        return true;
    }
}